﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Susam
{
    enum RoleSelection
    {
        None,
        All,
        Selected
    }

    public partial class Configuration : Form
    {

        private RoleSelection _contributorRoleSelection;
        private ConfigurationOptions _options;
        delegate void ButtonOperationCallback();
        public Configuration()
        {
            InitializeComponent();
            _contributorRoleSelection = RoleSelection.None;
        }

        void Subscribe(BackgorundScanner b)
        {
            b.BackgroundScanEnded += new BackgroundScanEndedHandler(FinalizeScan);
        }

        private void FinalizeScan()
        {
            this.EnableRescanButton();
        }

        private void EnableRescanButton()
        {
            // This pattern is needed for thread safety.
            if (this.buttonRescan.InvokeRequired)
            {
                ButtonOperationCallback d = new ButtonOperationCallback(EnableRescanButton);
                if (!this.IsDisposed)
                {
                    this.Invoke(d);
                }
            }
            else
            {
                this.buttonRescan.Enabled = true;
            }
        }

        private void DisableRescanButton()
        {
            // This pattern is needed for thread safety.
            if (this.buttonRescan.InvokeRequired)
            {
                ButtonOperationCallback d = new ButtonOperationCallback(DisableRescanButton);
                this.Invoke(d);
            }
            else
            {
                this.buttonRescan.Enabled = false;
            }
        }

        private void Configuration_Load(object sender, EventArgs e)
        {
            _options = new ConfigurationOptions();
            foreach (var path in Properties.Settings.Default.ArchivePathList)
            {
                _options.pathList.Add(path);
            }
            RefreshPathList();
            //Scan Tab
            checkBoxEpub.Checked = Properties.Settings.Default.FileTypeEpub;
            checkBoxPDF.Checked = Properties.Settings.Default.FileTypePDF;
            checkBoxRemoveMissing.Checked = Properties.Settings.Default.RemoveMissingFiles;

            // People List Tab
            checkBoxTranslator.Checked = Properties.Settings.Default.IncludeTranslatorRole;
            checkBoxEditor.Checked = Properties.Settings.Default.IncludeEditorRole;
            checkBoxIllustrator.Checked = Properties.Settings.Default.IncludeIllustratorRole;
            checkBoxRedactor.Checked = Properties.Settings.Default.IncludeRedactorRole;
            _contributorRoleSelection = (RoleSelection)Properties.Settings.Default.ContributorRoleSelection;
            InitializeRoleSelection();

            DisableSaveButton();
        }

        private void buttonRescan_Click(object sender, EventArgs e)
        {
            groupBoxArchive.BackColor = Color.Transparent;
            _options.removeMissingFiles = checkBoxRemoveMissing.Checked;
            _options.fileOptions.scanEpubs = checkBoxEpub.Checked;
            _options.fileOptions.scanPDFs = checkBoxPDF.Checked;
            if (!_options.pathList.Any())
            {
                // TODO: Log an error
                groupBoxArchive.BackColor = Color.Crimson;
            }
            DisableRescanButton();
            this.Subscribe(BackgorundScanner.Instance);
            BackgorundScanner.Instance.RunWorkerAsync(_options);
            this.Close();
        }

        private void RefreshPathList()
        {
            listBoxPathList.Items.Clear();
            if (_options.pathList.Any())
            {
                groupBoxArchive.BackColor = Color.Transparent;
                EnableRescanButton();
                foreach (var path in _options.pathList)
                {
                    listBoxPathList.Items.Add(path);
                }
            }
            EnableSaveButton();
        }

        private void InitializeRoleSelection()
        {
            switch (_contributorRoleSelection)
            {
                case RoleSelection.None:
                    radioButtonNoRoles.Checked = true;
                    break;
                case RoleSelection.All:
                    radioButtonAllRoles.Checked = true;
                    break;
                case RoleSelection.Selected:
                    radioButtonSelectedRoles.Checked = true;
                    break;
                default:
                    Debug.WriteLine("Invalid selection, perhaps the value in the settings is set wrong!");
                    break;
            }
            SetRoleSelectionAvailability();
        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialogPath.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (!_options.pathList.Contains(folderBrowserDialogPath.SelectedPath))
                {
                    _options.pathList.Add(folderBrowserDialogPath.SelectedPath);
                    RefreshPathList();
                }
            }
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            if (null != listBoxPathList.SelectedItem)
            {
                _options.pathList.Remove((String)listBoxPathList.SelectedItem);
                RefreshPathList();
            }
        }

        private void checkBoxEpub_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

        private void checkBoxPDF_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

        private void checkBoxRemoveMissing_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            DisableSaveButton();
            // Scan Tab
            Properties.Settings.Default.FileTypeEpub = checkBoxEpub.Checked;
            Properties.Settings.Default.FileTypePDF = checkBoxPDF.Checked;
            Properties.Settings.Default.RemoveMissingFiles = checkBoxRemoveMissing.Checked;

            // People List Tab
            Properties.Settings.Default.IncludeTranslatorRole = checkBoxTranslator.Checked;
            Properties.Settings.Default.IncludeEditorRole = checkBoxEditor.Checked;
            Properties.Settings.Default.IncludeIllustratorRole = checkBoxIllustrator.Checked;
            Properties.Settings.Default.IncludeRedactorRole = checkBoxRedactor.Checked;
            Properties.Settings.Default.ContributorRoleSelection = (int)_contributorRoleSelection;

            Properties.Settings.Default.ArchivePathList.Clear();
            foreach (var path in _options.pathList)
            {
                Properties.Settings.Default.ArchivePathList.Add(path);
            }
        }

        private void EnableSaveButton()
        {
            this.buttonSave.Enabled = true;
        }

        private void DisableSaveButton()
        {
            this.buttonSave.Enabled = false;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void linkLabelMoreInfo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                linkLabelMoreInfo.LinkVisited = true;
                System.Diagnostics.Process.Start("http://www.loc.gov/marc/relators/relaterm.html");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to open web page.");
            }
        }

        private void radioButtonSelectedRoles_CheckedChanged(object sender, EventArgs e)
        {
            _contributorRoleSelection = RoleSelection.Selected;
            SetRoleSelectionAvailability();
            EnableSaveButton();

        }

        private void radioButtonAllRoles_CheckedChanged(object sender, EventArgs e)
        {
            _contributorRoleSelection = RoleSelection.All;
            SetRoleSelectionAvailability();
            EnableSaveButton();

        }

        private void radioButtonNoRoles_CheckedChanged(object sender, EventArgs e)
        {
            _contributorRoleSelection = RoleSelection.None;
            SetRoleSelectionAvailability();
            EnableSaveButton();
        }

        private void SetRoleSelectionAvailability()
        {
            if (radioButtonSelectedRoles.Checked)
            {
                checkBoxTranslator.Enabled = true;
                checkBoxEditor.Enabled = true;
                checkBoxIllustrator.Enabled = true;
                checkBoxRedactor.Enabled = true;
            }
            else
            {
                checkBoxTranslator.Enabled = false;
                checkBoxEditor.Enabled = false;
                checkBoxIllustrator.Enabled = false;
                checkBoxRedactor.Enabled = false;
            }
        }

        private void checkBoxTranslator_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

        private void checkBoxEditor_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

        private void checkBoxIllustrator_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

        private void checkBoxRedactor_CheckedChanged(object sender, EventArgs e)
        {
            EnableSaveButton();
        }

    }
}
